package com.example.ime;

import java.io.File;
import java.util.ArrayList;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class SimpleImeEnAdapter {

	/** Context */
	private final Context context;

	/** SQLiteDatabaseHelper */
	private DatabaseHelper myDbHelper;

	/** DB Object */
	private SQLiteDatabase myDb;

	/** Data Base Name */
	public static final String DATABASE_NAME = "en_dictionary";

	/** DB Version */
	private static final int DATABASE_VERSION = 1;

	/** Current Used Table */
	private String currentTable;

	/** Table NAMES */
	public static final String[] TABLE_NAMES = { "a", "b", "c", "d", "e", "f",
			"g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s",
			"t", "u", "v", "w", "x", "y", "z" };

	// -------------------------------------------------------
	// FIELD_NAME
	// -------------------------------------------------------
	public static final String FIELD_TEXT = "text"; // Text

	public static final String FIELD_LEVEL = "level";

	public static final String FIELD_ABBRIVIATION = "abbriviation"; // Text

	public static final String FIELD_SIZE = "size"; // Int

	// (ex. apple/ number1 = a/ number2 =ap/ number3 = app/ number4 = appl/
	// number5 = apple)
	public static final String FIELD_NUMBER = "number"; // Text

	public static final String FIELD_COUNT = "count"; // Int

	// -----------------------------------------------------
	/**
	 * Constructor for SimpleImeEnAdapter
	 */
	// -----------------------------------------------------
	public SimpleImeEnAdapter(Context ctx) {
		this.context = ctx;
	}

	// -----------------------------------------------------
	/**
	 * Open Database and return SimpleImeEnAdapter Instance.
	 */
	// -----------------------------------------------------
	public SimpleImeEnAdapter open() throws SQLException {
		myDbHelper = new DatabaseHelper(context);
		myDb = myDbHelper.getWritableDatabase();
		return this;
	}

	// -----------------------------------------------------
	/**
	 * Search words
	 */
	// -----------------------------------------------------
	public synchronized ArrayList<String> searchWords(String key,
			float frequency) {
		ArrayList<String> list = new ArrayList<String>();

		// Check the First Letter
		boolean isFirstLetterUpperCase = false;
		if (key.length() == 0) {
			return list;
		}
		isFirstLetterUpperCase = Character.isUpperCase(key.charAt(0));
		key = key.toLowerCase();

		// Get Target Table
		String table = getTable(key);
		if (table == null) {
			return list;
		}
		currentTable = table;

		// Execute Query
		Cursor cursor = null;

		if (cursor == null || cursor.getCount() == 0) {
			// Try Ambiguous Match Search
			int keyLength = key.length();

			if (keyLength == 1) {
				// Short Word Search
				cursor = myDb.query(true, table, new String[] { FIELD_TEXT },
						FIELD_SIZE + " <=  3 and " + FIELD_NUMBER + keyLength
								+ " = " + "'" + key + "'" + " and "
								+ FIELD_LEVEL + " <= 2", null, null, null,
						FIELD_COUNT + " desc," + FIELD_TEXT + " asc", null);
			} else if (keyLength <= 10) {
				// Middle Word Search
				cursor = myDb.query(true, table, new String[] { FIELD_TEXT },
						FIELD_NUMBER + keyLength + " = " + "'" + key + "'"
								+ " and " + FIELD_LEVEL + " <= 2", null, null,
						null, FIELD_COUNT + " desc," + FIELD_TEXT + " asc",
						null);
			} else {		
				// Long Word Search
				String shortenKey = key.substring(0, 10);
				cursor = myDb.query(true, table, new String[] { FIELD_TEXT },
						FIELD_NUMBER + "10 = '" + shortenKey + "'" + " and "
								+ FIELD_TEXT + " like " + "'" + key + "%'"
								+ " and " + FIELD_LEVEL + " <= 2", null, null,
						null, FIELD_COUNT + " desc," + FIELD_TEXT + " asc",
						null);

			}

		}

		// Extract value from Cursor
		if (cursor != null) {
			while (cursor.moveToNext()) {
				String word = cursor.getString(cursor
						.getColumnIndex(FIELD_TEXT));

				// Change the first letter to upper case
				if (isFirstLetterUpperCase) {
					word = String
							.valueOf(Character.toUpperCase(word.charAt(0)))
							+ word.substring(1, word.length());
				}

				list.add(word);
			}
		}
		cursor.close();

		return list;
	}

	// -----------------------------------------------------
	/**
	 * Get Target Table Name from Key String.
	 */
	// -----------------------------------------------------
	private String getTable(String key) {

		for (int i = 0; i < TABLE_NAMES.length; i++) {
			String table = TABLE_NAMES[i];
			if (key.length() >= table.length()) {
				if (key.indexOf(table) == 0) {
					return table;
				}
			}
		}

		return null;
	}

	// -----------------------------------------------------
	/**
	 * Count Up Selected word (for learning)
	 */
	// -----------------------------------------------------
	public void countUp(String text) {

		try {

			// Get Current Count Value
			int currentCount = 0;
			Cursor cursor = myDb.query(true, currentTable,
					new String[] { FIELD_COUNT }, FIELD_TEXT + " = " + "\""
							+ text + "\"", null, null, null, null, null);

			if (cursor != null) {
				while (cursor.moveToNext()) {
					currentCount = cursor.getInt(cursor
							.getColumnIndex(FIELD_COUNT));
					break;
				}
				cursor.close();
			}

			// Set New Count
			int newCount = currentCount + 1;
			ContentValues values = new ContentValues();
			values.put(FIELD_COUNT, newCount);
			myDb.update(currentTable, values, FIELD_TEXT + "=" + "\"" + text
					+ "\"", null);

		} catch (Exception e) {}

	}

	// -----------------------------------------------------
	/**
	 * Clear Learning Data
	 */
	// -----------------------------------------------------
	public void clearLearning() {

		for (int i = 0; i < TABLE_NAMES.length; i++) {

			String table = TABLE_NAMES[i];
			ContentValues values = new ContentValues();
			values.put(FIELD_COUNT, 0);
			myDb.update(table, values, FIELD_COUNT + " > 0", null);

		}
	}

	// -----------------------------------------------------
	/**
	 * Check If Database already exists. 
	 * It will create first DB if not exists.
	 */
	// -----------------------------------------------------
	public boolean isDatabaseExist() {

		File dbFile = context.getDatabasePath(DATABASE_NAME);
		if (dbFile.exists()) {
			return true;
		} else {

			// Open for Create DB File
			DatabaseHelper helper = new DatabaseHelper(context);
			helper.getReadableDatabase();
			helper.close();

			return false;
		}

	}

	// -----------------------------------------------------
	/**
	 * Database Handle Class
	 */
	// -----------------------------------------------------
	public class DatabaseHelper extends SQLiteOpenHelper {

		public DatabaseHelper(Context context) {
			super(context, DATABASE_NAME, null, DATABASE_VERSION);
		}

		// -----------------------------------------------------
		/**
		 * Called only when DB is first Created
		 * 
		 * you can check the DB file at /data/data/[package-name]/databases
		 */
		// -----------------------------------------------------
		@Override
		public void onCreate(SQLiteDatabase db) {
		}

		// -----------------------------------------------------
		/**
		 * Called when DB is Updated
		 */
		// -----------------------------------------------------
		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		}

	}

}
